#include "dialog_configsystermparas.h"
#include "ui_dialog_configsystermparas.h"

#include "HttpRequest.h"

#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>

Dialog_configSystermParas::Dialog_configSystermParas(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_configSystermParas)
{
    ui->setupUi(this);

    initIniManager();

    readIni();
}

Dialog_configSystermParas::~Dialog_configSystermParas()
{
//    disconnect(ui->LineEdit_netIP, &QLineEdit::textChanged, this, &Dialog_configSystermParas::do_TextChanged);

    if(m_iniManager != nullptr)
    {
        delete m_iniManager;
    }

    delete ui;
}

void Dialog_configSystermParas::on_btn_save_clicked()
{
    writeIni();
    accept();
}


void Dialog_configSystermParas::on_btn_cancel_clicked()
{
    reject();
}

QString Dialog_configSystermParas::removePrefix(const QString &str, const QString &prefix) {  
    if (str.startsWith(prefix)) {  
        return str.mid(prefix.length()); // 去除前缀，返回剩余部分  
    }  
    return str; // 如果没有前缀，则返回原字符串  
}

void Dialog_configSystermParas::writeIni()
{
    saveSystemConfig();

    saveIPConfig();

    saveTimeConfig();

    saveCsvConfig();
}



void Dialog_configSystermParas::saveSystemConfig()
{
//    QSettings settings("./config/systemConfig.ini", QSettings::IniFormat);
//    settings.beginGroup("system");
    QString Group = "system";

    m_iniManager->writeValue(Group, "plcModbousSerialtest", ui->LineEdit_PlcInterfacePath->text());
//    m_iniManager->writeValue(Group, "netIP", ui->LineEdit_netIP->text());
    m_iniManager->writeValue(Group, "netIP", ui->IPAddressWidget->getIP());
    m_iniManager->writeValue(Group, "netPort", ui->LineEdit_netPort->text());
    m_iniManager->writeValue(Group, "configFilePath", ui->LineEdit_configFilePath->text());
    m_iniManager->writeValue(Group, "topCameraFocusRingNuberOf1", ui->LineEdit_topCameraFocusRingNuberOf1->text());
    m_iniManager->writeValue(Group, "topCameraLightNuberOf1", ui->LineEdit_topCameraLightNuberOf1->text());
    m_iniManager->writeValue(Group, "LineEdit_sideCameraFocusRingNuberOf1", ui->LineEdit_sideCameraFocusRingNuberOf1->text());
    m_iniManager->writeValue(Group, "LineEdit_sideCameraLightNuberOf1", ui->LineEdit_sideCameraLightNuberOf1->text());
    m_iniManager->writeValue(Group, "bottomCameraLightNuberOf2", ui->LineEdit_bottomCameraLightNuberOf2->text());
}

void Dialog_configSystermParas::saveIPConfig()
{
    QString Group = "system";

    QString netIP = m_iniManager->readValue(Group, "netIP").toString();

    QString netPort = m_iniManager->readValue(Group, "netPort").toString();

    HttpRequest::setRequestHeader( netIP + ":" + netPort);
}

void Dialog_configSystermParas::saveCsvConfig()
{
    QString Group = "CSV";

    QString csvPath = ui->le_csvFilePath->text().trimmed();

    if(m_iniManager->writeValue(Group, "Path", csvPath))
    {
        qDebug() << "CSV路径配置，写入成功！";
    } else {
        qDebug() << "CSV路径配置，写入失败！";
    }
}

void Dialog_configSystermParas::readSystemData()
{
    // 系统设置
    QString Group = "system";
    ui->LineEdit_PlcInterfacePath->setText(removePrefix(m_iniManager->readValue(Group, "plcModbousSerialtest").toString(), m_prefix));
//    ui->LineEdit_netIP->setText(m_iniManager->readValue(Group, "netIP").toString());
    ui->IPAddressWidget->setIP(m_iniManager->readValue(Group, "netIP").toString());

    ui->LineEdit_netPort->setText(m_iniManager->readValue(Group, "netPort").toString());
    ui->LineEdit_configFilePath->setText(m_iniManager->readValue(Group,"configFilePath").toString());
    ui->LineEdit_topCameraFocusRingNuberOf1->setText(removePrefix(m_iniManager->readValue(Group,"topCameraFocusRingNuberOf1").toString(), m_prefix));
    ui->LineEdit_topCameraLightNuberOf1->setText(removePrefix(m_iniManager->readValue(Group,"topCameraLightNuberOf1").toString(), m_prefix));
    ui->LineEdit_sideCameraFocusRingNuberOf1->setText(removePrefix(m_iniManager->readValue(Group,"LineEdit_sideCameraFocusRingNuberOf1").toString(), m_prefix));
    ui->LineEdit_sideCameraLightNuberOf1->setText(removePrefix(m_iniManager->readValue(Group,"LineEdit_sideCameraLightNuberOf1").toString(), m_prefix));
    ui->LineEdit_bottomCameraLightNuberOf2->setText(removePrefix(m_iniManager->readValue(Group,"bottomCameraLightNuberOf2").toString(), m_prefix));

}

void Dialog_configSystermParas::saveTimeConfig()
{
    QVariantMap map = getLineEditConfigMap();
//    qDebug() << "map:" << map;
    if(m_iniManager->writeValues("TIME", map))
    {
        qDebug() << "配置保存成功！";
//        showLog("配置保存成功！", LogType::Success);
    } else {
//        showLog("配置保存失败！", LogType::Error);
        qDebug() << "配置保存失败！";
    }
}

void Dialog_configSystermParas::initIniManager()
{
//    QString iniFilePath = tr("./config/configTime.ini");
    QString iniFilePath = tr("./config/systemConfig.ini");

    m_iniManager = new iniManager(iniFilePath, this);

    QFileInfo iniFile(iniFilePath);

        // 检查INI文件是否存在
        if (!iniFile.exists()) {
            qDebug() << QString(" %1 文件不存在，自动创建文件并初始化配置参数...").arg(iniFilePath);
//            showLog(QString(" %1 文件不存在，自动创建文件并初始化配置参数...").arg(iniFilePath), LogType::Error);

            // 写入初始值
            saveTimeConfig();

            LineEditAllClear();
        } else {
            qDebug() << QString(" %1 文件存在，读取配置参数...").arg(iniFilePath);
//            showLog(QString(" %1 文件存在，读取配置参数...").arg(iniFilePath), LogType::Success);

            readTimeData();
        }
}

QVariantMap Dialog_configSystermParas::getConfigMap()
{
    QVariantMap map;

    QString Group = "TIME";

    QString initTime =              m_iniManager->readValue(Group, "initTime").toString().trimmed();
    QString topPhotoTime =          m_iniManager->readValue(Group, "topPhotoTime").toString().trimmed();
    QString AFacePhotoTime =        m_iniManager->readValue(Group, "AFacePhotoTime").toString().trimmed();
    QString BFacePhotoTime =        m_iniManager->readValue(Group, "BFacePhotoTime").toString().trimmed();
    QString CFacePhotoTime =        m_iniManager->readValue(Group, "CFacePhotoTime").toString().trimmed();
    QString DFacePhotoTime =        m_iniManager->readValue(Group, "DFacePhotoTime").toString().trimmed();
    QString bottomPhotoTime =       m_iniManager->readValue(Group, "bottomPhotoTime").toString().trimmed();
    QString cuttingTime =           m_iniManager->readValue(Group, "cuttingTime").toString().trimmed();
//    QString resertTime =            m_iniManager->readValue("TIME", "resertTime").toString().trimmed();

    map.insert("initTime", initTime);
    map.insert("topPhotoTime", topPhotoTime);
    map.insert("AFacePhotoTime", AFacePhotoTime);
    map.insert("BFacePhotoTime", BFacePhotoTime);
    map.insert("CFacePhotoTime", CFacePhotoTime);
    map.insert("DFacePhotoTime", DFacePhotoTime);
    map.insert("bottomPhotoTime", bottomPhotoTime);
    map.insert("cuttingTime", cuttingTime);
//    map.insert("resertTime", resertTime);

    return map;
}


QVariantMap Dialog_configSystermParas::getLineEditConfigMap()
{
    QVariantMap map;

    QString initTime =              ui->le_initTime->text().trimmed();
    QString topPhotoTime =          ui->le_topPhotoTime->text().trimmed();
    QString AFacePhotoTime =        ui->le_AFacePhotoTime->text().trimmed();
    QString BFacePhotoTime =        ui->le_BFacePhotoTime->text().trimmed();
    QString CFacePhotoTime =        ui->le_CFacePhotoTime->text().trimmed();
    QString DFacePhotoTime =        ui->le_DFacePhotoTime->text().trimmed();
    QString bottomPhotoTime =       ui->le_bottomPhotoTime->text().trimmed();
    QString cuttingTime =           ui->le_cuttingTime->text().trimmed();
//    QString resertTime =            ui->le_resetTime->text().trimmed();

    map.insert("initTime", initTime);
    map.insert("topPhotoTime", topPhotoTime);
    map.insert("AFacePhotoTime", AFacePhotoTime);
    map.insert("BFacePhotoTime", BFacePhotoTime);
    map.insert("CFacePhotoTime", CFacePhotoTime);
    map.insert("DFacePhotoTime", DFacePhotoTime);
    map.insert("bottomPhotoTime", bottomPhotoTime);
    map.insert("cuttingTime", cuttingTime);
//    map.insert("resertTime", resertTime);

    return map;
}

void Dialog_configSystermParas::setLineEditConfigMap(const QVariantMap &map_config)
{
    if(map_config.isEmpty())
    {
        qDebug() << "空数据...";

        return;
    }

    QString initTime =          map_config.value("initTime").toString();
    QString topPhotoTime =      map_config.value("topPhotoTime").toString();
    QString AFacePhotoTime =    map_config.value("AFacePhotoTime").toString();
    QString BFacePhotoTime =    map_config.value("BFacePhotoTime").toString();
    QString CFacePhotoTime =    map_config.value("CFacePhotoTime").toString();
    QString DFacePhotoTime =    map_config.value("DFacePhotoTime").toString();
    QString bottomPhotoTime =   map_config.value("bottomPhotoTime").toString();
    QString cuttingTime =       map_config.value("cuttingTime").toString();
//    QString resertTime =        map_config.value("resertTime").toString();


    ui->le_initTime->setText(initTime);
    ui->le_topPhotoTime->setText(topPhotoTime);
    ui->le_AFacePhotoTime->setText(AFacePhotoTime);
    ui->le_BFacePhotoTime->setText(BFacePhotoTime);
    ui->le_CFacePhotoTime->setText(CFacePhotoTime);
    ui->le_DFacePhotoTime->setText(DFacePhotoTime);
    ui->le_bottomPhotoTime->setText(bottomPhotoTime);
    ui->le_cuttingTime->setText(cuttingTime);
//    ui->le_resetTime->setText(resertTime);
}


void Dialog_configSystermParas::LineEditAllClear()
{
    ui->le_initTime->clear();
    ui->le_topPhotoTime->clear();
    ui->le_AFacePhotoTime->clear();
    ui->le_BFacePhotoTime->clear();
    ui->le_CFacePhotoTime->clear();
    ui->le_DFacePhotoTime->clear();
    ui->le_bottomPhotoTime->clear();
    ui->le_cuttingTime->clear();
//    ui->le_resetTime->clear();
}

void Dialog_configSystermParas::readTimeData()
{
    // 读取设置
    QVariantMap map = getConfigMap();
    setLineEditConfigMap(map);
}

void Dialog_configSystermParas::readCsvFilePath()
{
    QString Group = "CSV";

    ui->le_csvFilePath->setText(m_iniManager->readValue(Group, "Path").toString());
}

void Dialog_configSystermParas::readIni() {

    readSystemData();

    readTimeData();

    readCsvFilePath();

    // 设置输入掩码为IPv4格式
//    ui->LineEdit_netIP->setInputMask("000.000.000.000;_");

//    connect(ui->LineEdit_netIP, &QLineEdit::textChanged, this, &Dialog_configSystermParas::do_TextChanged);

    ui->LineEdit_PlcInterfacePath->setStyleSheet("color:black");
    ui->LineEdit_configFilePath->setStyleSheet("color:black");
    ui->LineEdit_topCameraFocusRingNuberOf1->setStyleSheet("color:black");
    ui->LineEdit_topCameraLightNuberOf1->setStyleSheet("color:black");
    ui->LineEdit_sideCameraFocusRingNuberOf1->setStyleSheet("color:black");
    ui->LineEdit_sideCameraLightNuberOf1->setStyleSheet("color:black");
    ui->LineEdit_bottomCameraLightNuberOf2->setStyleSheet("color:black");

}


//void Dialog_configSystermParas::do_TextChanged(const QString &text)
//{
//    QString formattedText = text;

//        // 移除多余的点号
//        formattedText.remove(QRegExp("\\.{2,}"));

//        // 确保格式化为正确的IPv4地址格式
//        QRegExp ipFormat("^(?:\\d{1,3}\\.){0,3}\\d{0,3}$");
//        if (ipFormat.exactMatch(formattedText)) {
//            ui->LineEdit_netIP->blockSignals(true);
//            ui->LineEdit_netIP->setText(formattedText);
//            ui->LineEdit_netIP->blockSignals(false);
//        }
//}

void Dialog_configSystermParas::on_btn_seletFilePath_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    "选择CSV文件",
                                                    "C://Users//Mark//Desktop//csv",
                                                    tr("CSV文件(*.csv)"));

    if(fileName.isEmpty())
    {
//        if((QMessageBox::Ok == QMessageBox::question(this, "提示", "文件路径不能为空", QMessageBox::Ok)))
//        {

//        }
        qDebug() << "空文件路径...";
        return;
    }

//    m_fileName = fileName;
//    m_lastModified = QDateTime()

    ui->le_csvFilePath->setText(fileName);
}
